package kr.pe.johnkim.waiting.mobile.controller;

import kr.pe.johnkim.waiting.mobile.domain.WaitingMember;
import kr.pe.johnkim.waiting.mobile.util.WaitingCommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * 웹사이트에서 이벤트를 등록한 뒤 push notification 을 발송할때 호출하는 controller class 이다.
 * 외부에서 push notification 을 호출할때 사용한다.
 *
 * @author : John_Kim <cale9797@gmail.com>
 * @date : 13. 7. 2.
 */
@Controller
@RequestMapping(value = "/waitingNotificationController")
public class WaitingNotificationController {

    // SLF4J Logging
    private Logger logger = LoggerFactory.getLogger(WaitingNotificationController.class);

    @Autowired
    private WaitingCommon waitingCommon;

    /**
     * Android 사용자에게 Push Notification 을 보낸다.
     *
     * @param waitingMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/pushNotificationToAndroid", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public WaitingMember pushNotificationToAndroid(@RequestBody WaitingMember waitingMember) throws Exception {
        logger.info("pushNotificationToAndroid");

        WaitingMember result = new WaitingMember();

        try {
            waitingCommon.sendASMessage(waitingMember.getRegistrationId(), waitingMember.getMessageContent());
            result.setResult("SUCCESS");
            logger.info("success to send notification to android smart phone.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.error("fail to send notification to android smart phone.");
        }

        return result;
    }

    /**
     * iOS 사용자에게 Push Notification 을 보낸다.
     * 테스느용이며 운영계에 적용하기 전에 sendIPMessage() 로 수정 할 것.
     *
     * @param waitingMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/pushNotificationToiOS", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public WaitingMember pushNotificationToiOS(@RequestBody WaitingMember waitingMember) throws Exception {
        logger.info("pushNotificationToiOS");

        WaitingMember result = new WaitingMember();

        try {
            waitingCommon.sendIPMessage(waitingMember.getRegistrationId(), waitingMember.getMessageContent());
            result.setResult("SUCCESS");
            logger.info("success to send notification to iOS smart phone.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.error("fail to send notification to iOS smart phone.");
        }

        return result;
    }
}
